<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-bell"></i>{{$route.name}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-dialog :title="modalTitle" :visible.sync="dialogFormVisible">
                <el-form :model="addForm" :rules="rules" ref="addForm">
                    <!-- <el-form-item label="发布时间" :label-width="formLabelWidth">
                        <el-date-picker v-model="addForm.time" type="date" value-format="yyyy年MM月dd日" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item> -->
                    <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
                        <el-input type="text" v-model="addForm.title" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="作者" :label-width="formLabelWidth">
                        <el-input type="text" v-model="addForm.author" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="来源" :label-width="formLabelWidth">
                        <el-input type="text" v-model="addForm.origin" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="内容" :label-width="formLabelWidth">
                        <!-- <el-input type="textarea" v-model="addForm.content" auto-complete="off"></el-input> -->
                        <editor @input="htmlOutput" :htmlContent="addForm.content"></editor>
                    </el-form-item>
                    <el-form-item label="附件" :label-width="formLabelWidth">
                        <el-upload
                            action=""
                            multiple
                            :http-request="upload"
                            :on-remove="handleRemove"
                            :before-remove="beforeRemove"
                            :file-list="fileList"
                        >
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add">确 定</el-button>
                </div>
            </el-dialog>
            <el-input placeholder="输入标题" class="search" v-model="searchKey"></el-input>
            <el-button type="primary" icon="search" @click="search">搜索</el-button>
            <el-button type="primary" @click="addEx">新增公告</el-button>
            <el-dialog title="发送短信" :visible.sync="dialogFormMsg" close="onMsgClosed">
                <el-tree
                    :data="treeDatas"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    ref="tree"
                    highlight-current
                    :props="defaultProps"
                >
                </el-tree>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormMsg = false">取 消</el-button>
                    <el-button type="primary" @click="send">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <div>
          <el-table :data="initData" border fit style="width: 100%">
              <!-- <el-table-column prop="time" label="发布时间" show-overflow-tooltip>
              </el-table-column> -->
            <el-table-column prop="title" label="标题" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="author" label="作者" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="origin" label="来源" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="content" label="内容" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="state" label="状态" show-overflow-tooltip empty-text :formatter="stateFormatter">
            </el-table-column>
            <el-table-column prop="attach_list" label="附件" show-overflow-tooltip :formatter="attachFormatter">
            </el-table-column>
            <!-- <el-table-column label="阅读量" prop="click_times"></el-table-column> -->
            <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="statistics(scope.row)">统计</el-button>
                    <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
                    <el-button type="text" size="small" @click="delNotice(scope.row)">删除</el-button>
                    <el-button type="text" size="small" @click="sendMsg(scope.row)">发送短信</el-button>
                    <el-switch 
                        v-model="scope.row.state === 1 ? true : false" 
                        active-color="#13ce66"
                        @change="switchChange(scope.row)"
                    >
                    </el-switch>
                </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
            <el-pagination @current-change="handleCurrentChange" 
            :current-page="page.number" layout="total, prev, pager, next, jumper" 
            :total="page.total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import { notification, uploadFile, addressBook } from "../../server/getDate.js";
import Editor from './../../components/common/Editor';
import { mapState, mapActions } from 'vuex'
import { getStore, filterObj } from '../../utils/local.js'
const { list, add, deleteApi, update, disableApi } = notification
const { listApi, listCompanyApi, listDepartmenApi, sendApi } = addressBook
export default {
    components: {
        Editor
    },
    data() {
        return {
            dialogFormVisible: false,
            dialogFormMsg: false,
            modalTitle: '',
            addForm: {},
            formLabelWidth: '120px',
            searchKey: '',
            rules: {
                title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
            },
            fileList: [],
            treeDatas: [],
            treetTemporary: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            allUser: [], //存储所有部门下人员信息
            msgContent: ''
        }
    },
    created() {
        this.getList(1)
        this.getAddressBookCompany()
    },
    computed: mapState({
        initData: state => state.Notice.list,
        page: state => state.Notice.page,
        addressBooks: state => state.AddressBook.list,
        companyList: state => state.AddressBook.companyList,
        departmentList: state => state.AddressBook.departmentList
    }),
    methods: {
        ...mapActions(['save_list', 'saveCompanyList', 'saveDepartmentList', 'saveList']),
        edit(row) {
            this.dialogFormVisible = true
            this.modalTitle = '修改公告'
            this.addForm = filterObj(row)
            if (row.attach_list.length > 0) {
                this.fileList = row.attach_list.map(item => {
                    return {
                        name: item.attach_name,
                        url: item.url
                    }
                })
            }
        },
        getList(number) {
            const params = {
                page: number,
                pageSize: 10
            }
            if (this.searchKey !== '') {
                params.searchKey = this.searchKey
            }
            list({ ...params }).then(res => {
                if (res.code === '000000') {
                    this.save_list({
                        ...res,
                        number
                    })
                } else {
                    this.$message.error(res.message)
                }
            }).catch(err => {
                this.$message.error(err.message)
            })
        },
        search() {
            this.getList(this.page.number)
        },
        handleCurrentChange(val) {
            this.getList(val)
        },
        delNotice(row) {
            this.$confirm('此操作将永久删除该公告, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteApi({ ids: row.id }).then(res => {
                    if (res.code === '000000') {
                        this.$message.success('删除成功')
                        this.getList(this.page.number)
                    } else {
                        this.$message.error(err.message)
                    }
                }).catch(err => this.$message.error(err.message))
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        sendMsg(row) {
            this.msgContent = row.content || row.title
            this.dialogFormMsg = true
        },
        onMsgClosed() {
            this.treeDatas = []
        },
        //发送
        send() {
            console.log(this.$refs.tree.getCheckedKeys(), this.allUser);
            const checkedIds = this.$refs.tree.getCheckedKeys()
            if (checkedIds.length > 0) {
                const sendTels = []
                checkedIds.forEach(id => {
                    this.allUser.some(item => {
                        if (id === item.id) {
                            sendTels.push(item.user_tel)
                            return true
                        }
                    })
                })
                //发送短信
                this.sendMsgRequest(sendTels.join(','), this.msgContent)
            }
        },
        add(){
            this.$refs['addForm'].validate(valid => {
                if (valid) {
                    this.dialogFormVisible = false
                    const names = this.fileList.map(item => {
                        return item.name
                    })
                    const urls = this.fileList.map(item => {
                        return item.url
                    })
                    this.addForm.attachs = names.join(',')
                    this.addForm.attachUrls = urls.join(',')
                    if (this.addForm.id) {
                        this.updateInfo()
                    } else {
                        add({ ...this.addForm }).then(res => {
                            if (res.code === '000000') {
                                this.$message.success('添加成功')
                                this.getList(this.page.number)
                            } else {
                                this.$message.error(res.message)
                            }
                        }).catch(err => this.$message.error(err.message))
                    }
                }
            })
        },
        updateInfo() {
            update({ ...this.addForm }).then(res => {
                if (res.code === '000000') {
                    this.$message.success('修改成功')
                    this.getList(this.page.number)
                } else {
                    this.$message.error(res.message)
                }
            }).catch(err => this.$message.error('网络错误'))
        },
        addEx(){
            this.dialogFormVisible = true
            this.modalTitle = '新增公告',
            this.addForm = {}
            this.addForm.content = ''
            this.fileList = []
        },
        upload(value) {
            let formData = new FormData()
            formData.append('fileName', value.file)
            formData.append('fileType', '2')
            uploadFile(formData, res => {
                if (res.code === '000000') {
                    this.fileList.push({
                        name: res.result.originName,
                        url: res.result.storageName
                    })
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        htmlOutput(html) {
            console.log(html)
            this.addForm.content = html
        },
        switchChange(row) {
            disableApi({
                ids: row.id,
                state: row.state ? '0' : '1'
            }).then(res => {
                if (res.code === '000000') {
                    this.$message.success('修改成功')
                    this.getList(this.page.number)
                } else {
                    this.$message.error(res.message)
                }
            }, () => {
                this.$message.error('网络错误')
            })
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        handleRemove(file, fileList) {
            this.fileList = this.fileList.filter(item => {
                return item.names !== file.name
            })
        },
        stateFormatter(row) {
            return row.state === 1 ? '展示' : '不展示'
        },
        attachFormatter(row) {
            if (row.attach_list && row.attach_list.length > 0) {
                const names = row.attach_list.map(item => {
                    return item.attach_name
                })
                return names.join(',')
            } else {
                return '无附件'
            }
        },
        //单位
        getAddressBookCompany() {
            listCompanyApi().then(res => {
                if (res.code === '000000') {
                    const data = res.result
                    if (data.length > 0) {
                        data.forEach(item => {
                            this.getAddressBookDepartmen(item.id)
                            this.treetTemporary.push({
                                id: item.id,
                                label: item.name
                            })
                        })
                    }
                } else {
                    this.$message.error(res.message)
                }
            }, () => this.$message.error('网络错误'))
        },
        //单位部门
        getAddressBookDepartmen(id) {
            listDepartmenApi({ cId: id }).then(res => {
                if (res.code === '000000') {
                    const data = res.result
                    if (data.length > 0) {
                        data.forEach((item, index) => {
                            if (this.treetTemporary[index]) {
                                this.treetTemporary[index].children = []
                                this.treetTemporary[index].children.push({
                                    id: item.id,
                                    label: item.name
                                })
                            }
                            
                            this.getAddressBookList(id, item.id)
                        })
                    }
                } else {
                    this.$message.error(res.message)
                }
            }, () => this.$message.error('网络错误'))
        },
        //部门人员
        getAddressBookList(cId, dId) {
            listApi({ cId, dId }).then(res => {
                if (res.code === '000000') {
                    const data = res.result
                    if (data.length > 0) {
                        data.forEach((item, index) => {
                            this.allUser.push(item)
                            if (this.treetTemporary[index].children[index]) {
                                this.treetTemporary[index].children[index].children = []
                                this.treetTemporary[index].children[index].children.push({
                                    id: item.id,
                                    label: item.user_name
                                })
                            }
                        })
                        this.treeDatas = this.treetTemporary
                    }
                } else {
                    this.$message.error(res.message)
                }
            }, () => this.$message.error('网络错误'))
        },
        sendMsgRequest(uTels, msgContent) {
            sendApi({ uTels, msgContent }).then(res => {
                this.dialogFormMsg = false
                if (res.code === '000000') {
                    this.$message.success('发送成功')
                } else {
                    this.$message.error(res.message)
                }
            }, () => this.$message.error('网络错误'))
        },
        statistics(row) {
            this.$router.push({
                path: `/notifTongji?id=${row.id}`
            })
        }
  }


}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
}

.block {
  text-align: center;
  margin-top: 1%;
}
</style>
